<template>
	<view class="login-container">
		<!-- 头部区域 -->
		<view class="header">
			<!-- 背景图片 -->
			<image class="header-bg" :src="IMAGE_URL + '/static/images/login-bg.png'" mode="aspectFill"></image>
			
			<view class="logo-container">
				<u-image class="logo" :src="IMAGE_URL + '/static/logo.png'" width="96rpx" height="116rpx" mode="aspectFit"></u-image>    
			</view>
			<text class="app-name">雄安小管家</text>
			<text class="app-name-en">XIONGANXIAOGUANJIA</text>
			<text class="slogan">万家所需一键通达</text>
		</view>
		
		<!-- 表单区域 -->
		<view class="form-container">
			<!-- 手机号输入框 -->
			<view class="input-item">
                <span class="iconfont input-icon icon-phone"></span>
				<input 
					class="input-field" 
					type="text" 
					placeholder="请输入手机号"
					v-model="formData.phone"
					maxlength="11"
					@input="clearError('phone')"
				/>
			    <view v-if="error.phone" class="error-tip">{{ error.phone }}</view>

			</view>

			<!-- 密码登录模式 -->
			<template v-if="loginType === 'password'">
				<view class="input-item">
                    <span class="iconfont input-icon icon-mima"></span>
					
					<input 
						class="input-field" 
						type="password" 
						placeholder="请输入密码"
						v-model="formData.password"
						@input="clearError('password')"
					/>
					<view class="eye-icon" @click="togglePassword">
					    <span class="iconfont input-icon" :class="[!showPassword?'icon-yincangmima':'icon-ArtboardCopy']"></span>
					</view>
				    <view v-if="error.password" class="error-tip">{{ error.password }}</view>
				</view>
			</template>

			<!-- 验证码登录模式 -->
			<template v-else>
				<view class="input-item">
                    <span class="iconfont input-icon icon-yanzhengma"></span>
					<input 
						class="input-field" 
						type="text" 
						placeholder="请输入验证码"
						v-model="formData.code"
						maxlength="6"
						@input="clearError('code')"
					/>
					<text class="get-code-btn" :class="{disabled: codeTimer>0}" @click="getCodeEvent">{{ codeTimer>0 ? codeTimer+'s' : '获取验证码' }}</text>
				    <view v-if="error.code" class="error-tip">{{ error.code }}</view>
				</view>
			</template>

			<!-- 操作链接 -->
			<view class="action-links" :style="{'justify-content':loginType==='password'?'space-between':'flex-end'}">
				<text class="forget-pwd" v-if="loginType==='password'" @click="forgetPassword">忘记密码?</text>
				<text class="code-login" @click="toggleLoginType">{{ loginType==='password' ? '验证码登录' : '密码登录' }}</text>
							
			</view>
			
			<!-- 登录按钮 -->
			<button class="login-btn" @click="handleLogin">立即登录</button>
			<text class="forget-pwd">还没账号？</text><text class="login-text" @click="toReset">去注册</text>
			
		
			<!-- 协议文本 -->
			<view class="agreement">
				<text class="agreement-text">登录即同意</text>
				<text class="agreement-link" @click="showUserAgreement">《用户协议》</text>
				<text class="agreement-text">和</text>
				<text class="agreement-link" @click="showPrivacyPolicy">《隐私协议》</text>
			</view>
		</view>
	</view>
</template>

<script>
// 导入工具函数和接口
import { phoneVerification } from '@/utils/utils'
import { getCode, loginPassword, loginCode, wxLoginCode } from '@/api/index.js'
import appConfig from '@/config/app.js'

export default {
	data() {
		return {
			IMAGE_URL: appConfig.IMAGE_URL,
			// 表单数据
			formData: {
				phone: '',      // 手机号
				password: '',   // 密码
				code: ''        // 验证码
			},
			// 错误信息
			error: {
				phone: '',      // 手机号错误信息
				password: '',   // 密码错误信息
				code: ''        // 验证码错误信息
			},
			loginType: 'password',  // 登录类型：'password' 密码登录，'code' 验证码登录
			codeTimer: 0,          // 验证码倒计时
			codeTimerId: null      ,// 倒计时定时器ID
			showPassword:false
		}
	},
	methods: {

		onGetUserInfo(e) {
			console.log(e)
		},

		/**
		 * 切换登录类型（密码登录/验证码登录）
		 */
		toggleLoginType() {
			this.loginType = this.loginType === 'password' ? 'code' : 'password';
			this.clearAllError(); // 切换登录类型时清除所有错误信息
		},
		togglePassword() {
			this.showPassword = !this.showPassword;
		},
		/**
		 * 清除所有错误信息
		 */
		clearAllError() {
			this.error = { phone: '', password: '', code: '' };
		},
		
		/**
		 * 清除指定字段的错误信息
		 * @param {string} field 字段名
		 */
		clearError(field) {
			this.error[field] = '';
		},
		/**
		 * 获取验证码事件处理
		 */
		getCodeEvent() {
			// 防止重复点击（倒计时期间不允许再次获取）
			if (this.codeTimer > 0) return;
			
			// 验证手机号格式
			const phoneTip = phoneVerification(this.formData.phone);
			if (phoneTip) {
				this.error.phone = phoneTip;
				return;
			}
			
			// 调用接口发送验证码
			getCode({
				phone: this.formData.phone
			}).then(res => {
				if (res.errno === 0) {
					// 发送成功，显示成功提示
					uni.showToast({ title: '验证码已发送', icon: 'success' });
					// TODO: 这里应该启动倒计时，防止用户频繁点击
					this.codeTimer = 60
					const times = setInterval(() => {
						this.codeTimer --;
						if (this.codeTimer == 0) {
							this.codeTimer = null
							clearInterval(times);
						}
					}, 1000);
				} else {
					// 发送失败，显示错误信息
					uni.showToast({ 
						title: res.msg || '验证码发送失败', 
						icon: 'none' 
					});
				}
			}).catch(err => {
				// 接口调用异常处理
				console.error('获取验证码失败:', err);
				uni.showToast({ 
					title: '网络异常，请稍后再试', 
					icon: 'none' 
				});
			});
		},
		/**
		 * 处理登录按钮点击事件
		 * 进行表单验证，验证通过后调用登录接口
		 */
		handleLogin() {
			let valid = true; // 表单验证标志
			
			// 1. 手机号校验
			let phoneTip = phoneVerification(this.formData.phone);
			if (phoneTip) {
				this.error.phone = phoneTip;
				valid = false;
			} else {
				this.error.phone = ''; // 清除手机号错误信息
			}
			
			// 2. 根据登录类型进行相应验证
			if (this.loginType === 'password') {
				// 密码登录：验证密码
				if (!this.formData.password) {
					this.error.password = '密码不能为空';
					valid = false;
				} else {
					this.error.password = ''; // 清除密码错误信息
				}
			} else {
				// 验证码登录：验证验证码
				if (!this.formData.code) {
					this.error.code = '验证码不能为空';
					valid = false;
				} else {
					this.error.code = ''; // 清除验证码错误信息
				}
			}
			
			// 3. 如果验证不通过，直接返回，不执行登录
			if (!valid) return;
			
			// 4. 验证通过，调用登录接口
			this.loginEvent();
		},
		/**
		 * 执行登录接口调用
		 * 根据登录类型调用相应的登录接口（密码登录或验证码登录）
		 */
		loginEvent() {
			// 显示登录加载状态
			uni.showLoading({ title: '登录中...' });
			
			// 根据登录类型选择相应的登录接口
			const loginPromise = this.loginType === 'password' 
				? loginPassword({
					phone: this.formData.phone,
					password: this.formData.password
				})
				: loginCode({
					phone: this.formData.phone,
					code: this.formData.code
				});
			
			// 处理登录接口响应
			loginPromise.then(res => {
				uni.hideLoading(); // 隐藏加载状态
				
				if (res.errno === 0) {
					// 登录成功：将token和用户信息保存到全局store
					this.$store.dispatch('login', {
						token: res.data.token,
						user_info: res.data
					}).then(() => {
						// 显示登录成功提示
						uni.showToast({ title: '登录成功', icon: 'success' });
						
						// 延时跳转，优先返回登录前记录的页面
						setTimeout(() => {
							uni.reLaunch({ url: '/pages/main?url=0' })
						}, 500);
					});
				} else {
					// 登录失败：显示服务器返回的错误信息
					uni.showToast({ 
						title: res.msg || '登录失败', 
						icon: 'none' 
					});
				}
			}).catch(err => {
				// 接口调用异常处理
				uni.hideLoading(); // 隐藏加载状态
				console.error('登录失败:', err);
				uni.showToast({ 
					title: '登录失败，请稍后再试', 
					icon: 'none' 
				});
			});
		},
		/**
		 * 跳转到忘记密码页面
		 */
		forgetPassword() {
			uni.navigateTo({ url: '/views-master/login/forget-password' });
		},
		/* 去注册 */
		toReset(){
			uni.navigateTo({
				url:`/views-master/login/reset-password`
			})
		},
		/**
		 * 游客浏览（跳转到首页，无需登录）
		 */
		goBrowse() {
			uni.reLaunch({ url: '/pages/main?url=0' });
		},
		
		/**
		 * 微信登录功能
		 * TODO: 当前为开发中状态，后续需要实现完整的微信登录流程
		 */
		wechatLogin() {
			// uni.showToast({ title: '微信登录功能开发中', icon: 'none' });
			
			// 微信登录完整实现代码（待开发）
			wxLoginCode().then(code => {
				wxLogin({ code }).then(res => {
					if (res.success) {
						// 保存用户信息到store
						this.$store.dispatch('login', {
							token: res.data.token,
							user_info: res.data.user_info
						});
						uni.showToast({ title: '登录成功', icon: 'success' });
						uni.switchTab({ url: '/' });
					} else {
						uni.showToast({ title: res.message || '登录失败', icon: 'none' });
					}
				}).catch(err => {
					uni.showToast({ title: '登录失败，请稍后再试', icon: 'none' });
				});
			}).catch(err => {
				uni.showToast({ title: '获取微信登录信息失败', icon: 'none' });
			});

		},
		
		/**
		 * 显示用户协议
		 * TODO: 待实现用户协议页面
		 */
		showUserAgreement() {
			uni.showToast({ title: '用户协议功能开发中', icon: 'none' });
		},
		
		/**
		 * 显示隐私政策
		 * TODO: 待实现隐私政策页面
		 */
		showPrivacyPolicy() {
			uni.showToast({ title: '隐私协议功能开发中', icon: 'none' });
		}
		
	
		
	},
	
	/**
	 * 组件销毁前的清理工作
	 * 清除验证码倒计时定时器，防止内存泄漏
	 */
	beforeDestroy() {
		if (this.codeTimerId) {
			clearInterval(this.codeTimerId);
		}
	},
	
}
</script>

<style lang="scss" scoped>
.login-container {
	min-height: 100vh;
	background: #FFFFFF;
	position: relative;
}

.header {
    position: relative;
    box-sizing: border-box;
    width: 100%;
    height: 394rpx;
	text-align: center;
    padding-top: 104rpx;
}

.header-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
}
	
	.logo-container {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 1;
		.logo {
			width: 96rpx;
			height: 116rpx;
		}
	}
	
	.app-name {
		position: relative;
		display: block;
        font-family: Alimama FangYuanTi VF, Alimama FangYuanTi VF;
        font-weight: 600;
        font-size: 40rpx;
        color: #0080CC;
        letter-spacing: 1px;
        z-index: 1;
	}
	
	.app-name-en {
		position: relative;
		display: block;
        font-family: Alimama FangYuanTi VF, Alimama FangYuanTi VF;
		font-size: 12rpx;
        letter-spacing: 1px;
        color: #0080CC;
		margin-bottom: 10rpx;
        z-index: 1;
	}
	
	.slogan {
        position: relative;
        font-family: Alibaba PuHuiTi, Alibaba PuHuiTi;
		display: block;
		font-weight: 400;
		font-size: 24rpx;
		color: #666666;
        z-index: 1;
	}

.form-container {
    margin-top: 40rpx;
	padding: 0 32rpx;
	
	.input-item {
        position: relative;
		display: flex;
		align-items: center;
		background: #EEFAFF;
		border-radius: 96rpx;
		padding: 0 42rpx;
        height: 96rpx;
        margin-bottom: 28rpx;

        &:nth-child(1) {
            margin-bottom: 60rpx;
        }
		
		.input-icon {
			margin-right: 20rpx;
		}
		
		.input-field {
			flex: 1;
			font-size: 28rpx;
			color: #333;
			background: transparent;
		}
		.get-code-btn {
			color: #0785CF;
			font-size: 28rpx;
			margin-left: 20rpx;
			font-weight: 500;
			cursor: pointer;
			&.disabled {
				color: #bbb;
				pointer-events: none;
			}
		}
	}
		.eye-icon {
			width: 40rpx;
			height: 40rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;
		}
	.error-tip {
        position: absolute;
		color: #e43d33;
		font-size: 24rpx;
        bottom: -40rpx;
        left: 40rpx;
		line-height: 1.5;
		font-family: Alibaba PuHuiTi, Alibaba PuHuiTi;
	}
	
	.action-links {
		display: flex;
		justify-content: space-between;
		margin-bottom: 54rpx;
		
		
	}
	.forget-pwd, .code-login {
		font-family: Alibaba PuHuiTi, Alibaba PuHuiTi;
	    font-weight: 400;
	    font-size: 28rpx;
	    color: #666666;
	}
	.login-text{
		font-family: Alibaba PuHuiTi, Alibaba PuHuiTi;
		font-weight: 400;
		font-size: 28rpx;
		color: #0785CF;
	}
	
	.login-btn {
		width: 100%;
		height: 90rpx;
		color: #fff;
		font-size: 32rpx;
		font-weight: bold;
		border: none;
		margin-bottom: 28rpx;
        background: #0785CF;
        box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(0,0,0,0.1);
        border-radius: 60rpx 60rpx 60rpx 60rpx;
	}
	
	.browse-btn {
		display: block;
		text-align: center;
		font-size: 30rpx;
		color: #2196F3;
		margin-bottom: 194rpx;
	}
	
	.divider {
		position: relative;
		text-align: center;
		margin-bottom: 40rpx;
		
		
		.divider-text {
			padding: 0 30rpx;
			font-size: 24rpx;
            color: #666666;
			position: relative;
			z-index: 1;
		}
	}
	
	.wechat-login {
        width: 90rpx;
        height: 90rpx;
        border-radius: 50%;
        background-color: #f5f5f5;
		margin:0 auto 28rpx;
        display: flex;
        align-items: center;
        justify-content: center;

		.auth-btn {
			width: 90rpx;
			height: 90rpx;
			background-color: #f5f5f5;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		
		.wechat-icon {
			width: 90rpx;
			height: 90rpx;
		}
	}
	
	.agreement {
		width: 100%;
		position: fixed;
		bottom: 90rpx;
		text-align: center;
		font-size: 24rpx;
		color: #999;
		line-height: 1.5;

		.agreement-text {
			color: #999;
		}
		
		.agreement-link {
			color: #0785CF;
		}
	}
}

</style> 